#!/bin/bash

print_usage()
{
   echo "Usage: $0 <input file> <output path>"
   echo "Update D6 files format"
}

inputpath=$1
outputpath=$2

if [ "x$outputpath" == "x" ]; then
   echo "[ERROR] All arguments not available."
   print_usage
   exit 1
fi

lockfile="/tmp/update_d6_format.lock" 
echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Checking lock file $lockfile ..."
if [ -f $lockfile ]; then 
    echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Lock file exits! Aborting ..." 
    exit
fi

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Creating lock file ..."
`touch /tmp/update_d6_format.lock` 

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Processing ... "

tmpfile=/tmp/updated6.tmp

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Listing files from $inputpath ... "

#for f in `ls /data/samba_share/archives/huizhou/client_file/20070520/*.txt`
find >$tmpfile $inputpath -maxdepth 1 -name "*.D6"

C=`cat $tmpfile | wc -l`
if [ $C -eq 0 ]; then
    echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: No file found."
else

    for i in `cat $tmpfile`
      do
      #echo i $i
      # get IMEI number from file name
      b=`basename $i`
      #filename=`echo $b | awk -F "." '{ print $1 }'`
      imei=`echo $b | awk -F "." '{ print $1 }'`
      #echo filename $filename
      #imei=`echo $filename | sed s/[^0-9]//g`
      #echo imei $imei
    
      tmpfile1=/tmp/$imei.tmp
      
      echo $imei';' > $tmpfile1
      
      # update input file format to valid format
      echo `cat $i` | sed 's/[^0-9;]//g' >> $tmpfile1
      
      echo `cat $tmpfile1` | sed 's/ //g' > $outputpath/$imei.D6
      rm -f $tmpfile1
      rm -f $i
    done
      
fi

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: End of Process."

echo "`date +'%Y/%m/%d %H:%M:%S'` BASH SCRIPT: Deleting lock file..."
rm $lockfile
rm $tmpfile
